﻿#include "websocketclient.h"
#include <QDebug>

WebSocketClient::WebSocketClient(const QUrl &url,QObject *parent) : QObject(parent)
{
    // 连接 WebSocket 的信号槽
    connect(&m_webSocket, &QWebSocket::connected, this, &WebSocketClient::onConnected);
    connect(&m_webSocket, &QWebSocket::disconnected, this, &WebSocketClient::onDisconnected);
    connect(&m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived);

    // 打开 WebSocket 连接
    qDebug() << "Connecting to WebSocket server at" << url;
    m_webSocket.open(url);
}

WebSocketClient::~WebSocketClient()
{
    m_webSocket.close();  // 关闭 WebSocket 连接
}

void WebSocketClient::onConnected()
{
    qDebug() << "WebSocket connected";
    // 连接成功后，发送一条消息
    m_webSocket.sendTextMessage(QStringLiteral("Hello from WebSocket Client!"));
}

void WebSocketClient::onTextMessageReceived(const QString &message)
{
    qDebug() << "Message received from server:" << message;
}

void WebSocketClient::onDisconnected()
{
    qDebug() << "WebSocket disconnected";
}
